<template>
  <div class="menu-content">
    <!-- 搜索栏卡片 -->
    <el-card class="card-container search-card">
      <div class="search-container">
        <div class="search-input-group">
          <!-- 添加@input和@clear事件处理 -->
          <el-input v-model="searchParams.keyword" placeholder="请输入序号" class="search-input" clearable
            @input="searchMaintenanceLogs" @clear="searchMaintenanceLogs">
            <template #prefix>
              <el-icon class="el-input__icon">
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-button type="primary" @click="searchMaintenanceLogs" class="search-button">搜索</el-button>
        </div>
        <el-button type="primary" class="add-button" @click="showAddLogDialog = true"><el-icon>
            <Plus />
          </el-icon> 添加维护日志</el-button>
      </div>
    </el-card>

    <!-- 表格卡片 -->
    <el-card class="card-container table-card">
      <el-table :data="paginatedLogs" stripe border class="custom-table rounded-table">
        <!-- 添加序号列 -->
        <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
        <!-- 修改维护人为用户ID -->
        <el-table-column prop="userId" label="用户ID" align="center"></el-table-column>
        <el-table-column prop="maintainTime" label="维护时间" align="center"></el-table-column>
        <el-table-column prop="log" label="维护内容" align="center"></el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="currentPage" :total="total" layout="total, prev, pager, next, jumper"
          :prev-text="'上一页'" :next-text="'下一页'" @current-change="handleCurrentChange">
          <template #format-total="{ total }">总计 {{ total }} 条</template>
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加维护日志对话框 -->
    <el-dialog v-model="showAddLogDialog" title="添加维护日志" width="500px">
      <!-- 确保 ref 属性值为 logFormRef -->
      <el-form :model="newMaintenanceLog" :rules="addLogRules" ref="logFormRef">
        <!-- 删除维护日期输入框 -->
        <el-form-item label="维护内容" prop="log">
          <el-input v-model="newMaintenanceLog.log" type="textarea" rows="4"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddLogDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAddLog">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'; // 添加onMounted
import { Search, Plus } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
// 删除：import { submitDailyLog } from '@/utils/api';
import request from '@/utils/request'; // 新增：导入request

export default {
  name: 'MaintenanceLogs',
  components: { Search, Plus },
  setup() {
    const searchParams = ref({ keyword: '' });
    // 删除虚拟数据：const originalLogs = ref([...]);
    const originalLogs = ref([]); // 初始化为空数组
    const maintenanceLogs = ref([]); // 初始化为空数组
    const showAddLogDialog = ref(false);
    const newMaintenanceLog = reactive({
      maintainTime: null,
      log: ''
    });
    // 添加表单引用声明
    const logFormRef = ref(null);
    const addLogRules = {
      // 删除维护时间验证规则（已移除该字段）
      log: [
        { required: true, message: '请输入维护日志内容', trigger: 'blur' },
        { min: 5, message: '日志内容至少5个字符', trigger: 'blur' }
      ]
    };

    const currentPage = ref(1);
    const total = ref(maintenanceLogs.value.length);

    const paginatedLogs = computed(() => {
      const pageSize = 10;
      const startIndex = (currentPage.value - 1) * pageSize;
      const endIndex = startIndex + pageSize;
      return maintenanceLogs.value.slice(startIndex, endIndex);
    });

    const searchMaintenanceLogs = () => {
      const keyword = searchParams.value.keyword.trim();
      if (!keyword) {
        // 如果搜索框为空，显示所有日志
        maintenanceLogs.value = [...originalLogs.value];
        total.value = originalLogs.value.length;
        currentPage.value = 1;
        return;
      }
      // 尝试将搜索关键词转换为数字
      const searchIndex = parseInt(keyword, 10);
      if (!isNaN(searchIndex)) {
        // 精确匹配序号（序号是从1开始的）
        const filtered = originalLogs.value.filter((item, index) => index + 1 === searchIndex);
        maintenanceLogs.value = filtered;
        total.value = filtered.length;
        currentPage.value = 1;
      } else {
        // 如果不是数字，显示无结果
        maintenanceLogs.value = [];
        total.value = 0;
        currentPage.value = 1;
      }
    };

    const submitAddLog = async () => {
      // 通过 ref 获取表单实例
      const valid = await logFormRef.value.validate();
      if (!valid) return;

      try {
        // 修改为正确的参数传递方式（query参数）
        const response = await request.post('/users/submitDailyLog', {}, {
          params: {
            log: newMaintenanceLog.log
          }
        });

        // 检查响应是否存在
        if (!response) {
          ElMessage.error('提交失败: 未收到响应');
          return;
        }

        // 保持原状态码判断
        if (response.code === 200) {
          ElMessage.success('维护日志提交成功');
          // 添加到本地列表时自动生成当前时间
          const today = new Date().toISOString().split('T')[0];
          const newLog = {
            maintainer: '当前用户',
            maintainTime: today,
            log: newMaintenanceLog.log
          };
          maintenanceLogs.value.push(newLog);
          originalLogs.value.push(newLog);
          total.value = maintenanceLogs.value.length;
          // 关闭对话框并重置表单
          showAddLogDialog.value = false;
          newMaintenanceLog.log = '';
          logFormRef.value.resetFields();
        } else {
          ElMessage.error(`提交失败: ${response.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('提交日志出错:', error);
        // 统一错误处理逻辑（删除了重复的错误状态判断）
        const errorMsg = error.response?.data?.msg || error.message || '提交失败，请重试';
        ElMessage.error(errorMsg);
      }
    };

    const handleCurrentChange = (page) => {
      currentPage.value = page;
    };

    // 修改时间格式化函数，增强兼容性和错误处理
    const formatTime = (timeString) => {
      if (!timeString) return '未知时间';

      // 尝试多种时间格式解析
      let date;
      if (timeString instanceof Date) {
        date = timeString;
      } else if (typeof timeString === 'string') {
        // 移除可能的时区信息（如+08:00）
        const cleanedTime = timeString.replace(/\+\d{2}:\d{2}$/, '');
        date = new Date(cleanedTime);
      }

      // 验证日期有效性
      if (isNaN(date.getTime())) {
        console.error('无效的时间格式:', timeString);
        return '格式错误';
      }

      // 格式化日期为 YYYY-MM-DD HH:MM:SS
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}:${date.getSeconds().toString().padStart(2, '0')}`;
    };

    // 添加后端数据获取方法
    const fetchMaintenanceLogs = async () => {
      try {
        const response = await request.get('/users/getMyDailyMaintenance');
        console.log('完整响应数据:', response);
        if (response && response.code === 200) {
          console.log('后端返回数据:', response.data);
          if (Array.isArray(response.data)) {
            const formattedData = response.data.map((item, index) => ({
              userId: item.userId || item.user_id || '未知ID',
              maintainer: item.username || item.maintainerName || '未知',
              // 增加详细日志以便调试
              maintainTime: formatTime(item.maintainTime || item.createTime || item.submissionTime),
              log: item.log,
              // 添加原始时间字段用于调试
              rawTime: item.maintainTime || item.createTime || item.submissionTime
            }));
            originalLogs.value = formattedData;
            maintenanceLogs.value = formattedData;
            total.value = formattedData.length;
          } else {
            ElMessage.error('后端返回数据格式错误，期望数组');
          }
        } else {
          ElMessage.error(`获取失败: ${response?.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('请求异常详情:', error);
        ElMessage.error(`网络错误: ${error.message || '连接失败'}`);
      }
    };

    // 组件挂载时获取数据
    onMounted(() => {
      fetchMaintenanceLogs();
    });

    return {
      searchParams,
      maintenanceLogs,
      paginatedLogs,
      searchMaintenanceLogs,
      currentPage,
      total,
      handleCurrentChange,
      // 添加对话框相关变量和方法
      showAddLogDialog,
      newMaintenanceLog,
      addLogRules,
      submitAddLog,
      // 添加这行导出表单引用
      logFormRef,
      fetchMaintenanceLogs // 导出方法（如果需要）
    };
  }
};
</script>

<style scoped>
/* 卡片容器样式 */
.card-container {
  width: 90%;
  margin: 0 auto 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-card {
  padding: 20px;
  margin-top: 20px;
}

.table-card {
  padding: 20px;
}

/* 搜索区域样式 */
.search-container {
  display: flex;
  justify-content: space-between;
  /* 修改为两端对齐 */
  align-items: center;
  padding: 10px 0;
}

.search-input-group {
  display: flex;
  gap: 10px;
  align-items: center;
  width: 50%;
  /* 设置搜索组宽度 */
}

.search-input {
  flex: 1;
  /* 让输入框占满剩余空间 */
  max-width: none;
  /* 移除最大宽度限制 */
}

.search-button {
  min-width: 80px;
  /* 设置按钮最小宽度 */
}

.add-button {
  white-space: nowrap;
  /* 防止按钮文字换行 */
}

/* 表格样式 */
::v-deep .custom-table {
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e8e8e8;
  min-height: 400px;
  /* 拉长表格 */
  width: 100% !important;
  /* 确保表格宽度 */
}

::v-deep .custom-table .el-table__header-wrapper th {
  background-color: #1890ff !important;
  color: white !important;
  font-weight: 500;
  border-bottom: 2px solid white !important;
}

/* 优化表格行基础样式 */
/* 表格行悬浮效果 - 三级选择器保障 */
/* 第一级：表格行基础样式 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row {
  transition: all 0.2s ease;
  position: relative;
}

/* 第二级：行悬浮样式 */
::v-deep .custom-table .el-table__body-wrapper .el-table__row:hover {
  transform: scale(1.01);
  transform-origin: center left;
  color: #fff !important;
  font-size: 15px;
  z-index: 10;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 0 5px;
}

/* 第三级：单元格悬浮样式（最高优先级保障） */
::v-deep .custom-table .el-table__body-wrapper .el-table__row:hover td {
  background-color: #1890ff !important;
}

/* 确保表格有足够宽度容纳放大后的内容 */
::v-deep .el-table__body {
  width: 100% !important;
}

/* 悬浮行中的文本按钮文字变白 */
::v-deep .el-table__row:hover .el-button--text {
  color: #fff !important;
}

/* 分页容器样式 */
.pagination-container {
  margin-top: 20px;
  text-align: center;
  position: static;
  bottom: auto;
  left: auto;
  transform: none;
  background-color: transparent;
  padding: 0;
  box-shadow: none;
}

/* 对话框样式保留 */
.el-dialog .el-form-item {
  margin-bottom: 15px;
}
</style>